/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.easoft.code.pos.ui.beans;

import com.easoft.code.pos.App;
import com.easoft.code.pos.data.dao.GenericDao;
import com.easoft.code.pos.data.exception.CoreDataLayerException;
import com.easoft.code.pos.data.pojos.Producto;
import com.easoft.code.pos.data.util.QueryParameter;
import com.easoft.code.pos.ui.models.PojoTableModel;
import com.easoft.code.pos.util.UIUtil;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Eliu
 */
public class FormPOSBusquedaProds extends javax.swing.JDialog {

    private final PojoTableModel searchModel;
    private final GenericDao dao = GenericDao.getMe();
    private static List<Producto> localProducs;
    private Producto selProduct;

    public FormPOSBusquedaProds() {
        super(App.mainForm, "Busqueda de Productos", true);
        Frame parent = App.mainForm;
        if (parent != null) {
            Dimension parentSize = parent.getSize();
            Point p = parent.getLocation();
            setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
        }

        initComponents();
        reloadProducts();
        searchModel = new PojoTableModel(localProducs,
                Arrays.asList(new String[]{"Codigo",
                    "Nombre", "Precio Compra"}),
                Arrays.asList(new String[]{"Codigo",
                    "Nombre", "PrecioCosto"}), Producto.class);

        tableResults.setModel(searchModel);

        setSize(new Dimension(500, 300));
        setVisible(true);
    }

    public Producto getSelProduct() {
        return selProduct;
    }

    public void setSelProduct(Producto selProduct) {
        this.selProduct = selProduct;
    }

    private void reloadProducts() {
        try {
            if (localProducs == null || localProducs.isEmpty()) {
                localProducs = (List<Producto>) dao.doNamedQuery("Producto.findAll", new QueryParameter[]{},
                        Producto.class, false);
            }

        } catch (CoreDataLayerException ex) {
            Logger.getLogger(FormPOSBusquedaProds.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormAutoriza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormAutoriza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormAutoriza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormAutoriza.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                FormPOSBusquedaProds dialog = new FormPOSBusquedaProds();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtCodigoProd = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNombreProducto = new javax.swing.JTextField();
        btnCleanFiltro = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableResults = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        btnAdd = new javax.swing.JButton();

        setTitle("Busqueda Productos");
        setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText("Codigo:");
        jPanel3.add(jLabel1);

        txtCodigoProd.setText("[codigo]");
        txtCodigoProd.setPreferredSize(new java.awt.Dimension(60, 20));
        txtCodigoProd.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCodigoProdFocusLost(evt);
            }
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCodigoProdFocusGained(evt);
            }
        });
        txtCodigoProd.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoProdKeyReleased(evt);
            }
        });
        jPanel3.add(txtCodigoProd);

        jLabel2.setText("Nombre:");
        jPanel3.add(jLabel2);

        txtNombreProducto.setText("[nombre]");
        txtNombreProducto.setPreferredSize(new java.awt.Dimension(150, 20));
        txtNombreProducto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNombreProductoFocusLost(evt);
            }
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtNombreProductoFocusGained(evt);
            }
        });
        txtNombreProducto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreProductoKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreProductoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNombreProductoKeyReleased(evt);
            }
        });
        jPanel3.add(txtNombreProducto);

        btnCleanFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon-16-delete.png"))); // NOI18N
        btnCleanFiltro.setText("Limpiar");
        btnCleanFiltro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCleanFiltroActionPerformed(evt);
            }
        });
        jPanel3.add(btnCleanFiltro);

        getContentPane().add(jPanel3, java.awt.BorderLayout.PAGE_START);

        jPanel1.setLayout(new java.awt.BorderLayout());

        tableResults.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableResults.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableResultsMouseClicked(evt);
            }
        });
        tableResults.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableResultsKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tableResults);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add-4.png"))); // NOI18N
        btnAdd.setText("Agregar");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jPanel2.add(btnAdd);

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCleanFiltroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanFiltroActionPerformed
        reloadProducts();
        searchModel.fireTableDataChanged();
    }//GEN-LAST:event_btnCleanFiltroActionPerformed

    private void txtNombreProductoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreProductoKeyPressed
        searchModel.filterStrigData("nombre", txtNombreProducto.getText());
        searchModel.fireTableDataChanged();
    }//GEN-LAST:event_txtNombreProductoKeyPressed

    private void txtCodigoProdFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCodigoProdFocusGained
        if (txtCodigoProd.getText().equals("[codigo]")) {
            txtCodigoProd.setText("");
        }
    }//GEN-LAST:event_txtCodigoProdFocusGained

    private void txtNombreProductoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNombreProductoFocusGained
        if (txtNombreProducto.getText().equals("[nombre]")) {
            txtNombreProducto.setText("");
        }
    }//GEN-LAST:event_txtNombreProductoFocusGained

    private void txtNombreProductoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreProductoKeyTyped
    }//GEN-LAST:event_txtNombreProductoKeyTyped

    private void txtNombreProductoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreProductoKeyReleased
        searchModel.filterStrigData("nombre", txtNombreProducto.getText());
        searchModel.fireTableDataChanged();
    }//GEN-LAST:event_txtNombreProductoKeyReleased

    private void txtCodigoProdKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoProdKeyReleased
        searchModel.filterStrigData("codigo", txtCodigoProd.getText());
        searchModel.fireTableDataChanged();
    }//GEN-LAST:event_txtCodigoProdKeyReleased

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        if (tableResults.getSelectedRow() < 0) {
            UIUtil.showError("No ha seleccionado ningun producto", "Agregar Producto");
        } else {
            setSelProduct((Producto) searchModel.getData().get(tableResults.getSelectedRow()));
            setVisible(false);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void tableResultsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableResultsMouseClicked
        if (evt.getClickCount() == 2) {
            btnAddActionPerformed(null);
        }
    }//GEN-LAST:event_tableResultsMouseClicked

    private void txtCodigoProdFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCodigoProdFocusLost
        txtCodigoProd.setText("[codigo]");
    }//GEN-LAST:event_txtCodigoProdFocusLost

    private void txtNombreProductoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNombreProductoFocusLost
        txtNombreProducto.setText("[nombre]");
    }//GEN-LAST:event_txtNombreProductoFocusLost

    private void tableResultsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableResultsKeyPressed
        if (evt.getKeyCode() == 13) {
            btnAddActionPerformed(null);
        }
    }//GEN-LAST:event_tableResultsKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCleanFiltro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableResults;
    private javax.swing.JTextField txtCodigoProd;
    private javax.swing.JTextField txtNombreProducto;
    // End of variables declaration//GEN-END:variables
}
